<script>
import { deepClone } from '../../utils/index'
import render from '../render/render.js'

const ruleTrigger = {
  'el-input': 'blur',
  'el-input-number': 'blur',
  'el-select': 'change',
  'el-radio-group': 'change',
  'el-checkbox-group': 'change',
  'el-cascader': 'change',
  'el-time-picker': 'change',
  'el-date-picker': 'change',
  'el-rate': 'change',
  'time-computed': 'blur',
  'input-number': 'blur'
}

const layouts = {
  colFormItem(h, scheme) {
    const config = scheme.__config__
    const listeners = buildListeners.call(this, scheme)

    let labelWidth = config.labelWidth ? `${config.labelWidth}px` : null
    if (config.showLabel === false) labelWidth = '0'
    if (this.detail) {
      if ([17].includes(scheme.__config__.componentType)) {
        let HH, MM
        if (scheme.__config__.defaultValue) {
          HH = parseInt(scheme.__config__.defaultValue / 60)
          MM = scheme.__config__.defaultValue % 60
        }
        return (
          <el-col type={scheme.type} span={config.span}>
            <el-form-item
              label-width={labelWidth}
              prop={scheme.__vModel__}
              label={config.showLabel ? config.label : ''}
            >
              <div class="inlineBlock">
                {HH} 小时 {MM} 分钟
              </div>
            </el-form-item>
          </el-col>
        )
      } else {
        return (
          <el-col type={scheme.type} span={config.span}>
            <el-form-item
              label-width={labelWidth}
              prop={scheme.__vModel__}
              label={config.showLabel ? config.label : ''}
            >
              <div class="inlineBlock">
                {scheme.__config__.defaultValue}
                {scheme.__slot__.append}
              </div>
            </el-form-item>
          </el-col>
        )
      }
    } else {
      return (
        <el-col type={scheme.type} span={config.span}>
          <el-form-item
            label-width={labelWidth}
            prop={scheme.__vModel__}
            label={config.showLabel ? config.label : ''}
          >
            <render conf={scheme} on={listeners} />
          </el-form-item>
        </el-col>
      )
    }
  },
  rowFormItem(h, scheme) {
    let child = renderChildren.apply(this, arguments)
    if (scheme.type === 'flex') {
      child = (
        <el-row type={scheme.type} justify={scheme.justify} align={scheme.align}>
          {child}
        </el-row>
      )
    }
    if (scheme.__config__.title !== undefined) {
      const currentItem = scheme
      let style = {
        fontSize: currentItem.__config__.fontSize + 'px',
        color: currentItem.__config__.color,
        textAlign: currentItem.__config__.textAlign,
        fontWeight: currentItem.__config__.fontWeight ? 'bold' : '',
        lineHeight: currentItem.__config__.lineHeight
          ? currentItem.__config__.lineHeight + 'px'
          : currentItem.__config__.fontSize + 'px'
      }
      return (
        <el-col span={scheme.__config__.span}>
          <el-row gutter={scheme.gutter}>
            <el-form-item label-width={'0px'}>
              <div style={style}>{scheme.__config__.title}</div>
            </el-form-item>
          </el-row>
        </el-col>
      )
    }
    return (
      <el-col span={scheme.span}>
        <el-row gutter={scheme.gutter}>{child}</el-row>
      </el-col>
    )
  }
}

function renderFrom(h) {
  const { formConfCopy } = this
  return (
    <el-row gutter={formConfCopy.gutter}>
      <el-form
        size={formConfCopy.size}
        label-position={formConfCopy.labelPosition}
        label-suffix={formConfCopy.labelSuffix}
        disabled={formConfCopy.disabled}
        label-width={`${formConfCopy.labelWidth}px`}
        ref={formConfCopy.formRef}
        // model不能直接赋值 https://github.com/vuejs/jsx/issues/49#issuecomment-472013664
        props={{ model: this[formConfCopy.formModel], autocomplete: 'off' }}
        rules={this[formConfCopy.formRules]}
      >
        {renderFormItem.call(this, h, formConfCopy.fields)}
        {formConfCopy.formBtns && formBtns.call(this, h)}
      </el-form>
    </el-row>
  )
}

function formBtns(h) {
  return (
    <el-col>
      <el-form-item size="large">
        <el-button type="primary" onClick={this.submitForm}>
          提交
        </el-button>
        <el-button onClick={this.resetForm}>重置</el-button>
      </el-form-item>
    </el-col>
  )
}

function renderFormItem(h, elementList) {
  return elementList.map((scheme) => {
    const config = scheme.__config__
    const layout = layouts[config.layout]

    if (layout) {
      return layout.call(this, h, scheme)
    }
    throw new Error(`没有与${config.layout}匹配的layout`)
  })
}

function renderChildren(h, scheme) {
  const config = scheme.__config__
  if (!Array.isArray(config.children)) return null
  return renderFormItem.call(this, h, config.children)
}

function changeValue(fields, key, value) {
  fields?.forEach((field) => {
    if (field.__config__.children) {
      changeValue.call(this, field.__config__.children, key, value)
    } else {
      if (field.__vModel__ === key) {
        this.$set(field.__config__, 'defaultValue', value)
        this.$set(this[this.formConf.formModel], key, value)
      }
    }
  })
}
function setValue(event, config, scheme, change) {
  if (change) {
    const { fields } = this.formConfCopy
    Object.keys(change).forEach((key) => {
      changeValue.call(this, fields, key, change[key])
    })
  }
  this.$set(config, 'defaultValue', event)
  this.$set(this[this.formConf.formModel], scheme.__vModel__, event)
}

function buildListeners(scheme) {
  const config = scheme.__config__
  const methods = this.formConf.__methods__ || {}
  const listeners = {}

  // 给__methods__中的方法绑定this和event
  Object.keys(methods).forEach((key) => {
    listeners[key] = (event) => methods[key].call(this, event)
  })
  // 响应 render.js 中的 vModel $emit('input', val)
  // console.log(listeners, 'listeners')
  listeners.input = (event, change) => setValue.call(this, event, config, scheme, change)
  return listeners
}

export default {
  components: {
    render
  },
  provide() {
    return {
      formSize: () => this.formConfCopy.size,
      detail: () => {
        return this.detail
      }
    }
  },
  props: {
    formConf: {
      type: Object,
      required: true
    },
    initData: {
      type: Object,
      default: () => ({})
    },
    detail: {
      type: Boolean,
      default: false
    }
  },
  data() {
    const formConfCopy = deepClone(this.formConf)
    const initFormData = (componentList) => {
      componentList.forEach((cur) => {
        if (cur.__config__.children) {
          initFormData(cur.__config__.children)
        } else {
          cur.__config__.defaultValue = this.initData?.[cur.__vModel__] ?? cur.__config__.defaultValue
          if (cur.children) initFormData(cur.children)
        }
      })
    }
    initFormData(formConfCopy.fields)
    const data = {
      formConfCopy,
      [this.formConf.formModel]: {},
      [this.formConf.formRules]: {}
    }
    this.initFormData(data.formConfCopy.fields, data[this.formConf.formModel], this.initData)
    this.buildRules(data.formConfCopy.fields, data[this.formConf.formRules])
    return data
  },
  methods: {
    initFormData(componentList, formData, initData = {}) {
      componentList.forEach((cur) => {
        const config = cur.__config__
        if (cur.__vModel__) formData[cur.__vModel__] = initData?.[cur.__vModel__] ?? config.defaultValue
        if (config.children) this.initFormData(config.children, formData, initData)
      })
      this.$forceUpdate()
    },
    buildRules(componentList, rules) {
      componentList.forEach((cur) => {
        const config = cur.__config__
        if (Array.isArray(config.regList)) {
          if (config.required) {
            const required = {
              required: config.required,
              message: cur.placeholder
            }
            if (Array.isArray(config.defaultValue)) {
              required.type = 'array'
              required.message = `请至少选择一个${config.label}`
            }
            required.message === undefined && (required.message = `${config.label}不能为空`)
            config.regList.push(required)
          }
          rules[cur.__vModel__] = config.regList.map((item) => {
            item.pattern && (item.pattern = eval(item.pattern))
            item.trigger = ruleTrigger && ruleTrigger[config.tag]
            return item
          })
        }
        if (config.children) this.buildRules(config.children, rules)
      })
    },
    resetForm() {
      const formConfCopy = deepClone(this.formConf)
      const initFormData = (componentList) => {
        componentList.fields.forEach((cur) => {
          cur.__config__.defaultValue = this.initData?.[cur.__vModel__] ?? cur.__config__.defaultValue
          if (cur.children) initFormData(cur.children)
        })
      }
      initFormData(formConfCopy)
      this.formConfCopy = formConfCopy
      this.$refs[this.formConf.formRef].resetFields()
    },
    getFormData() {
      return this[this.formConf.formModel]
    },
    submitForm() {
      let state = false
      this.$refs[this.formConf.formRef].validate((valid) => {
        if (!valid) return (state = false)
        // 触发sumit事件
        this.$emit('submit', this[this.formConf.formModel])
        return (state = true)
      })
      return { state, data: this[this.formConf.formModel] }
    }
  },
  render(h) {
    return renderFrom.call(this, h)
  }
}
</script>
<style scoped>
.inlineBlock {
  display: inline-block;
}
</style>
